<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配送员姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入配送员姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['riderAccount:account:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['riderAccount:account:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['riderAccount:account:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="配送员ID" align="center" prop="riderId" />
      <el-table-column label="配送员姓名" align="center" prop="name" />
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="工作类型" align="center" prop="workType" />
      <el-table-column label="配送薪资" align="center" prop="deliverySalary" />
      <el-table-column label="奖励提成" align="center" prop="reward" />
      <el-table-column label="累计收入" align="center" prop="totalIncome" />
      <el-table-column label="已入账户额" align="center" prop="depositedAmount" />
      <el-table-column label="未入账户额" align="center" prop="unsettledAmount" />
      <el-table-column label="账户余额" align="center" prop="accountBalance" />
      <el-table-column label="账户状态" align="center" prop="accountStatus" />
      <el-table-column label="可提现金额" align="center" prop="withdrawableAmount" />
      <el-table-column label="保证金" align="center" prop="deposit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(scope.row)" v-hasPermi="['riderAccount:account:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click.stop="handleDelete(scope.row)" v-hasPermi="['riderAccount:account:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配送员账户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="accountRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="配送员ID" prop="riderId" v-if="isAdd">
          <el-select
              v-model="form.riderId"
              placeholder="请选择配送员ID"
              clearable
              @change="handleRiderChange"
          >
          <el-option
              v-for="rider in availableRiders"
              :key="rider.riderId"
              :label="`${rider.riderId}(${rider.name})`"
          :value="rider.riderId"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="骑手姓名" prop="name" v-if="isAdd">
          <el-input
              v-model="form.name"
              placeholder="选择配送员ID后自动填充"
              readonly
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone" v-if="isAdd">
          <el-input
              v-model="form.phone"
              placeholder="选择配送员ID后自动填充"
              readonly
          />
        </el-form-item>
        <el-form-item label="工作类型" prop="workType">
          <el-select v-model="form.workType" placeholder="请选择工作类型">
            <el-option label="兼职众包" value="兼职众包" />
            <el-option label="全职专送" value="全职专送" />
          </el-select>
        </el-form-item>

        <el-form-item label="配送薪资" prop="deliverySalary">
          <el-input v-model="form.deliverySalary" placeholder="请输入配送薪资" />
        </el-form-item>
        <el-form-item label="奖励提成" prop="reward">
          <el-input v-model="form.reward" placeholder="请输入奖励提成" />
        </el-form-item>
        <el-form-item label="累计收入" prop="totalIncome">
          <el-input v-model="form.totalIncome" placeholder="请输入累计收入" />
        </el-form-item>
        <el-form-item label="已入户额" prop="depositedAmount">
          <el-input v-model="form.depositedAmount" placeholder="请输入已入账户额" />
        </el-form-item>
        <el-form-item label="未入户额" prop="unsettledAmount">
          <el-input v-model="form.unsettledAmount" placeholder="请输入未入账户额" />
        </el-form-item>
        <el-form-item label="账户余额" prop="accountBalance">
          <el-input v-model="form.accountBalance" placeholder="请输入账户余额" />
        </el-form-item>
        <el-form-item label="可提现额" prop="withdrawableAmount">
          <el-input v-model="form.withdrawableAmount" placeholder="请输入可提现金额" />
        </el-form-item>
        <el-form-item label="保证金" prop="deposit">
          <el-input v-model="form.deposit" placeholder="请输入保证金" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Account">
import { useRouter } from 'vue-router';
import { listAccount, getAccount, delAccount, addAccount, updateAccount } from "@/api/riderAccount/account"
import {listRiderBasicInfo} from "@/api/system/RiderBasicInfo.js";
const router = useRouter();  // 获取路由实例
const { proxy } = getCurrentInstance()

const accountList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const riderIds = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const riderList = ref([])
const isAdd = ref(true) // true=新增，false=修改
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    phone: null,
    workType: null,
  },
  rules: {
  }
})
const query = reactive({
  pageNum: 1,
  pageSize: 100,
  riderId:'',
  name: '',
  phone: '',

  rules: {

    riderId: [
      { required: true, message: '请选择配送员ID', trigger: 'change' }
    ],

    name: [
      { required: true, message: '请选择配送员ID自动填充姓名', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请选择配送员ID自动填充手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ]
  }
});
const { queryParams, form, rules } = toRefs(data)

const existingRiderIds = computed(() => {
  return new Set(accountList.value.map(item => item.riderId))
})

const availableRiders = computed(() => {
  return riderList.value.filter(rider => !existingRiderIds.value.has(rider.riderId))
})

const handleRiderChange = (selectedRiderId) => {
  // 从骑手列表中找到选中的骑手
  const selectedRider = riderList.value.find(rider => rider.riderId === selectedRiderId)
  if (selectedRider) {
    // 同时填充姓名和手机号码
    form.value.name = selectedRider.name
    form.value.phone = selectedRider.phone
  } else {
    // 未找到时清空
    form.value.name = ''
    form.value.phone = ''
  }
}

function handleRowClick(row) {
    router.push({
    name: 'accountDetail',
    params: { riderId: row.riderId }
  });
}

/** 查询配送员账户列表 */
function getList() {
  loading.value = true
  listAccount(queryParams.value).then(response => {
    accountList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log("表格已有骑手ID：", accountList.value.map(item => item.riderId))
    console.log(total.value)
    // 表格加载后重新获取骑手列表，确保过滤基于最新数据
    getRiderList()
  })
}

//查询配送员基本信息表
function getRiderList() {
  loading.value = true
  listRiderBasicInfo(query).then(response => {
   riderList.value = response.rows
    loading.value = false
    // 打印所有骑手的riderId
    console.log("所有骑手ID：", riderList.value.map(item => item.riderId))
    // 打印过滤后的可用骑手ID（关键：看是否排除了表格中已有的ID）
    console.log("可用骑手ID：", availableRiders.value.map(item => item.riderId))
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    riderId: null,
    name: null,
    phone: null,
    workType: null,
    deliverySalary: null,
    reward: null,
    totalIncome: null,
    depositedAmount: null,
    unsettledAmount: null,
    accountBalance: null,
    accountStatus: null,
    withdrawableAmount: null,
    deposit: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("accountRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加配送员账户"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _riderId = row.riderId || riderIds.value
  getAccount(_riderId).then(response => {
    form.value = response.data
    console.log(response.data)
    isAdd.value = false // 标记为修改
    open.value = true
    title.value = "修改配送员账户"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["accountRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAccount(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAccount(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除配送员账户编号为"' + _ids + '"的数据项？').then(function() {
    return delAccount(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('riderAccount/account/export', {
    ...queryParams.value
  }, `account_${new Date().getTime()}.xlsx`)
}

getList()

</script>
